<template>
    <div class="ai-alarm-situation-analysis">
        <div class="tab">
            <div class="tab-group">
                <template v-for="(item, index) in tabList" :key="index">
                    <div :class="['tab-item', currentActiveIndex == index ? 'active' : '']" @click="changeTab(item, index)">
                        {{
                            item.title }}</div>
                </template>
            </div>
            <div class="panel">
                <div class="panel-container" v-for="(item, index) in options" :key="item.code">
                    <div class="title">
                        {{ item.title }}
                    </div>
                    <div class="detail">
                        <div class="bigsizenumber">
                            {{ item.value }}
                        </div>
                        <div class="text">
                            <div class="top">环比</div>
                            <div :class="['percent', item.annulus > 0 ? '' : 'down']">
                                <div class="img">
                                    <img :src="requireImgUrl('image', item.annulus > 0 ? '上升' : '下降')"
                                        :alt="item.annulus > 0 ? '上升' : '下降'" :title="item.annulus > 0 ? '上升' : '下降'">
                                </div>
                                <div class="number">
                                    {{ renderChain(item.annulus) }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="chart-container">
            <base-echart :show-no-data="true" :options="state.MonitorStatistics" height="250"></base-echart>
        </div>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, onUnmounted } from 'vue';
import { MonitorStatistics } from './config';
import { requireImgUrl } from '@/utils/localurl/metaUrl';
import { useIds } from '@/stores/screen/ids';
import { NewGeneral } from '@/api/screen/equipment';
import pLimit from 'p-limit';
import emits from '@/utils/emits';
const { getsessionStorage } = useIds();
const state = reactive<any>({ MonitorStatistics });
const tabList = [
    {
        title: "一般",
        code: "AI_ALERT_MESSAGE_DETAIL_LAST_7_DAY_INFO",
        class: "today",
    },
    {
        title: "告警",
        code: "AI_ALERT_MESSAGE_DETAIL_LAST_7_DAY_WARN",
        class: "nowWeek"
    },
    {
        title: "紧急",
        code: "AI_ALERT_MESSAGE_DETAIL_LAST_7_DAY_ERROR",
        class: "nowMonth"
    }
];
const currentActiveIndex = ref(1);
const changeTab = (item: object, index: number) => {
    currentActiveIndex.value = index;
    initData();
};
const renderChain = (number) => {
    let abs = Math.abs(number).toFixed(2);
    if (abs === 'Infinity') {
        abs = 100 + "%"
    }
    else if (Number(abs) > 100) {
        abs = 100 + "%"
    }
    else if (Object.is(abs, NaN)) {
        abs = 0 + "%"
    }
    else if (abs == 'NAN') {
        abs = 0 + "%"
    }
    else {
        abs = abs + "%"
    }
    return abs;
};
const getPastSevenDaysFormatted = (): string[] => {
    const today = new Date();
    const pastSevenDays = [];

    for (let i = 0; i < 7; i++) {
        const day = new Date(today);
        day.setDate(today.getDate() - i);
        const formattedDate = `${(day.getMonth() + 1).toString().padStart(2, '0')}-${day.getDate().toString().padStart(2, '0')}`;
        pastSevenDays.unshift(formattedDate);
    }

    return pastSevenDays;
};
const options = ref([
    {
        title: '昨日告警总数',
        code: 'AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT',
        value: 0,
        annulus: 0
    },

    {
        title: '今日告警总数',
        code: 'AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT',
        value: 0,
        annulus: 0
    }
]);

const getChartData = async () => {
    let config = [
        {
            code: tabList[currentActiveIndex.value].code,
            params: {
                equipmentIds: getsessionStorage()
            }
        }
    ];
    let res = await NewGeneral(config) as any;
    if (res.code === 200) {
        let date = new Date();
        let nowYear = date.getFullYear();
        let dayArr = getPastSevenDaysFormatted();
        let fulldayArr = getPastSevenDaysFormatted();
        fulldayArr = fulldayArr.map(item => {
            return nowYear + '-' + item
        });
        let seriesData = new Array(dayArr.length);
        state.MonitorStatistics.xAxis[0].data = dayArr;
        if (Object.keys(res.data).length === 0) {
            return;
        };
        if (res.data[`${tabList[currentActiveIndex.value].code}`].data.length > 0) {
            fulldayArr.forEach((day, i) => {
                seriesData[i] = 0;
                res.data[`${tabList[currentActiveIndex.value].code}`].data.forEach((last, index) => {
                    if (day === last.x) {
                        seriesData[i] = last.y;
                    };

                });
            });
            state.MonitorStatistics.series[0].data = seriesData;
        }
        else {
            dayArr.forEach((day, i) => {
                seriesData[i] = 0;
            });
            state.MonitorStatistics.series[0].data = seriesData;
        };
    };
};

const getAlarmData = async () => {
    let config = [];
    options.value.forEach(item => {
        config.push({
            code: item.code,
            params: {
                equipmentIds: getsessionStorage()
            }
        });
    });
    let res = await NewGeneral(config) as any;
    if (res.code === 200) {
        if (Object.keys(res.data).length === 0) {
            return;
        };
        options.value.forEach(item => {
            for (let key in res.data) {
                if (item.code == key) {
                    item.value = res.data[key].data;
                    if (item.code == 'AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT' && key == 'AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT') {
                        if (res.data['AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT'].data == 0 && res.data['AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT'].data == 0) {
                            item.annulus = 0
                        }
                        else {
                            let chain = ((res.data['AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT'].data - res.data['AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT'].data) / res.data['AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT'].data) * 100;
                            item.annulus = chain;
                        }
                    };
                    if (item.code == 'AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT' && key == 'AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT') {
                        if (res.data['AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT'].data == 0 && res.data['AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT'].data == 0) {
                            item.annulus = 0
                        }
                        else {
                            let chain = ((res.data['AI_ALERT_MESSAGE_DETAIL_YESTERDAY_EVENT'].data - res.data['AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT'].data) / res.data['AI_ALERT_MESSAGE_DETAIL_TODAY_EVENT'].data) * 100;
                            item.annulus = chain;
                        }
                    };
                };
            };
        });
    };

};
const initData = () => {
    //并发
    const limit = pLimit(1);
    //获取 首页3个统计数据
    const input = [limit(() => getChartData()), limit(() => getAlarmData())];
    Promise.all(input);
};
// 创建一个轮询器
const PollingTimer = ref(null);
const PollingFunction = () => {
    if (PollingTimer.value) {
        clearInterval(PollingTimer.value);
    };
    PollingTimer.value = setInterval(() => {
        initData();
    }, 30000);
};
onMounted(() => {
    initData();
    PollingFunction();
    emits.on("HANDLE_MESSAGE", initData);
});
onUnmounted(() => {
    emits.off("HANDLE_MESSAGE", initData);
    if (PollingTimer.value) {
        clearInterval(PollingTimer.value);
    };
});

</script>
<style lang="scss" scoped>
.ai-alarm-situation-analysis {
    width: 100%;
    height: 100%;
    padding: 5px;
    padding-bottom: 0;
    box-sizing: border-box;

    // 溢出
    overflow-y: auto;
    scrollbar-width: none;
    -ms-overflow-style: none;
    position: relative;

    &::-webkit-scrollbar {
        display: none;
        /* Chrome Safari */
    }

    .tab {
        position: absolute;
        width: 100%;
        height: clamp(3.438rem, 2.86vw, 6.875rem);
        top: 5%;
        z-index: 2;
        display: flex;

        .tab-group {
            width: 34%;
            height: clamp(1.563rem, 1.3vw, 3.125rem);
            display: flex;
            margin-right: 5px;

            .tab-item {
                width: clamp(2.5rem, 2.08vw, 5rem);
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
                color: rgba(136, 136, 136, 1);
                font-size: clamp(0.875rem, 0.73vw, 1.75rem);
                border: 1px solid rgba(136, 136, 136, 1);
                background-color: rgba(51, 51, 51, 0.60);
                cursor: pointer;
                text-overflow: ellipsis;
                white-space: nowrap;

                &:nth-child(1) {
                    border-radius: 4px 0 0 4px;
                }

                &:nth-child(2) {
                    border-left: 0;
                    border-right: 0;
                }

                &:nth-child(3) {
                    border-radius: 0 4px 4px 0;
                }

                &.active {
                    border-color: rgba(15, 148, 250, 1);
                    color: rgba(15, 148, 250, 1);
                    background-color: rgba(5, 45, 77, 0.60);
                    position: relative;

                    &:nth-child(2)::after {
                        content: "";
                        position: absolute;
                        width: 1px;
                        height: 100%;
                        background-color: rgba(15, 148, 250, 1);
                        left: -1px;
                        top: 0;
                    }

                    &:nth-child(2)::before {
                        content: "";
                        position: absolute;
                        width: 1px;
                        height: 100%;
                        background-color: rgba(15, 148, 250, 1);
                        right: -1px;
                        top: 0;
                    }

                }



            }

        }


        .panel {
            width: 65%;
            height: 100%;
            display: flex;
            justify-content: space-between;
            padding-right: 10px;
            box-sizing: border-box;

            .panel-container {
                width: 47%;
                height: 100%;

                .title {
                    width: 100%;
                    height: 35%;

                    color: white;
                    display: flex;
                    align-items: center;
                    font-size: clamp(0.75rem, 0.63vw, 1.5rem);
                }

                .detail {
                    width: 100%;
                    height: 65%;
                    display: flex;


                    .bigsizenumber {
                        width: 50%;
                        height: 100%;
                        font-size: clamp(1.5rem, 1.25vw, 3rem);
                        font-family: Microsoft YaHei, Microsoft YaHei;
                        font-weight: bold;
                        color: #E2F2FF;
                        letter-spacing: 2px;
                        text-shadow: 0px 0px 6px #26BEFF;
                    }

                    .text {
                        width: 50%;
                        height: 100%;
                        display: flex;
                        flex-direction: column;


                        .top {
                            display: flex;
                            align-items: center;
                            justify-content: flex-end;
                            width: 100%;
                            height: 50%;
                            font-size: clamp(0.75rem, 0.63vw, 1.5rem);
                            color: rgba(204, 204, 204, 1);
                        }

                        .percent {
                            width: 100%;
                            height: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: flex-end;
                            font-size: clamp(0.75rem, 0.63vw, 1.5rem);
                            color: #20CC65;

                            &.down {
                                color: #FF5252;
                            }

                            img {
                                display: block;
                                width: 16px;
                                height: 16px;
                            }

                        }
                    }

                }


            }
        }
    }

    .chart-container {
        width: 100%;
        height: 100%;
    }
}
</style>